package com.fzq.uilt;
import com.fzq.config.MinioConfig;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class MinioUtils {

    @Autowired
    MinioClient minioClient;
    @Autowired
    MinioConfig minioConfig;

    /**
     * 获取文件访问URL
     */
    public String getFileUrl(String fileName) {
        return generatePresignedUrl(fileName);
    }

    /**
     * 生成预签名URL（有时效性，更安全）
     */
    public String generatePresignedUrl(String fileName) {
        try {
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(minioConfig.getBucketName())
                            .object(fileName)
                            .expiry(7, TimeUnit.HOURS) // 7小时有效
                            .build()
            );
        } catch (Exception e) {
            throw new RuntimeException("生成文件URL失败", e);
        }
    }

    /**
     * 生成直接访问URL
     */
    public String generateDirectUrl(String fileName) {
        // 移除端点末尾的斜杠（如果有）
        String endpoint = minioConfig.getEndpoint().replaceAll("/$", "");
        return endpoint + "/" + minioConfig.getBucketName() + "/" + fileName;
    }

    /**
     * 生成下载URL（强制浏览器下载而不是预览）
     */
    public String generateDownloadUrl(String fileName, String downloadName) {
        try {
            if("".equals(downloadName)){
                downloadName = fileName;
            }
            Map<String, String> params = new HashMap<>();
            params.put("response-content-disposition",
                    "attachment; filename=\"" + downloadName + "\"");

            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(minioConfig.getBucketName())
                            .object(fileName)
                            .expiry(1, TimeUnit.HOURS)
                            .extraQueryParams(params)
                            .build()
            );
        } catch (Exception e) {
            return generateDirectUrl(fileName);
        }
    }

}